package net1;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Scanner;

public class TcpFileClient {
    private static final String host = "127.0.0.1";
    private static final int port = 8888;

    public static void main(String[] args) throws IOException {
        Scanner scanner = new Scanner(System.in);
        while (true) {
            Request request = build(scanner);
            Socket socket = new Socket(host, port);
            OutputStream outputStream = socket.getOutputStream();
            System.out.println("客户端发送请求：" + request);
            request.clientWrite(outputStream);

            InputStream inputStream = socket.getInputStream();
            Response response = Response.clientParse(inputStream);
            System.out.println("客户端收到响应: " + response);

            socket.close();
        }
    }

    private static Request build(Scanner scanner) throws IOException {
        System.out.println("-----------------------------");
        System.out.println("请输入要操作的类型：1（展示目录文件列表） 2（文件重命名） 3（删除文件） 4（上传文件） 5（下载文件）");
        Request request = new Request();
        int type = Integer.parseInt(scanner.nextLine());
        System.out.println("请输入要操作的路径：");
        String url = scanner.nextLine();
        String data = "";
        if (type == 2) {
            System.out.println("请输入要重命名的名称：");
            data = scanner.nextLine();
        } else if (type == 4) {
            System.out.println("请输入要上传的文件路径：");
            String upload = scanner.nextLine();
            data = new String(Files.readAllBytes(Paths.get(upload)));
        } else if (type != 1 && type != 3 && type != 5) {
            System.out.println("只能输入1-5的数字，请重新输入");
            return build(scanner);
        }
        request.setType(type);
        request.setUrl(url);
        request.setData(data);
        return request;
    }
}
